#include <cstring>
#include <cstdio>
#include <unistd.h>
#include <fcntl.h>
#include <iostream>
#include <vector>
#include <functional>
void setnonblock(int fd)
{
    int f1 = fcntl(fd, F_GETFL);
    if (f1 < 0)
    {
        std::cerr << "fcntl : " << strerror(errno) << std::endl;
        return;
    }
    fcntl(fd, F_SETFL, f1 | O_NONBLOCK);
}
void printlog()
{
    std::cout << "this is a log" << std::endl;
}
void download()
{
    std::cout << "ehis is a download" << std::endl;
}
void executeSql()
{
    std::cout << "this is a executeSql" << std::endl;
}
using func_t = std::function<void()>;
#define INIT(v)                  \
    do                           \
    {                            \
        v.push_back(printlog);   \
        v.push_back(download);   \
        v.push_back(executeSql); \
    } while (0);
#define EXEC_OTHER(cbs)            \
    do                             \
    {                              \
        for (auto const &cb : cbs) \
        {                          \
            cb();                  \
        }                          \
    } while (0);

void test()
{
    std::vector<func_t> cbs;
    INIT(cbs);
    setnonblock(0);
    char buffer[1024];
    while (true)
    {
        printf(">>> ");
        fflush(stdout);
        ssize_t s = read(0, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s - 1] = 0;
            std::cout << "echo# " << buffer << std::endl;
        }
        else if (s == 0)
        {
            std::cout << "read end" << std::endl;
            break;
        }
        else
        {
        }
        EXEC_OTHER(cbs);
        sleep(1);
    }
}
void test1()
{
    std::vector<func_t> cbs;
    INIT(cbs);
    setnonblock(0);
    char buffer[1024];
    while (true)
    {
        printf(">>> ");
        fflush(stdout);
        ssize_t s = read(0, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s - 1] = 0;
            std::cout << "echo# " << buffer << std::endl;
        }
        else if (s == 0)
        {
            std::cout << "read end" << std::endl;
            break;
        }
        else
        {
            if (errno == EAGAIN || errno == EWOULDBLOCK)
            {
                std::cout << "我没错, 只是没有数据" << std::endl;
                EXEC_OTHER(cbs);
            }
            else if (errno == EINTR)
            {
                continue;
            }
            else
            {
                std::cout << "result : " << s << " errno : " << strerror(errno) << std::endl;
                break;
            }
        }
        sleep(1);
    }
}
int main(int argc, char *argv[])
{
    test1();
    return 0;
}